from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app.services.ai_service import AIService
from app.models.objective import Objective
from app.models.project import Project
from app.models.status import StatusUpdate
from app.models.user import User

bp = Blueprint('query', __name__, url_prefix='/api/query')
ai_service = AIService()

@bp.route('', methods=['POST'])
@login_required
def natural_language_query():
    """自然语言查询"""
    data = request.get_json()
    query_text = data.get('query')

    if not query_text:
        return jsonify({'error': 'Query text required'}), 400

    # 收集相关上下文数据
    context = _gather_context()

    # 调用AI服务
    result = ai_service.query(query_text, context)

    if result['success']:
        return jsonify({
            'query': query_text,
            'response': result['response'],
            'model': result['model']
        }), 200
    else:
        return jsonify({
            'error': 'AI service error',
            'details': result.get('error')
        }), 500

@bp.route('/analyze-progress', methods=['POST'])
@login_required
def analyze_progress():
    """分析目标进度"""
    data = request.get_json()
    objective_ids = data.get('objective_ids', [])

    # 获取目标数据
    if objective_ids:
        objectives = Objective.query.filter(Objective.id.in_(objective_ids)).all()
    else:
        # 如果没有指定，获取当前用户的所有目标
        if current_user.is_manager():
            # 主管可以看到团队所有目标
            team_member_ids = [member.id for member in current_user.get_team_members()]
            team_member_ids.append(current_user.id)
            objectives = Objective.query.filter(Objective.owner_id.in_(team_member_ids)).all()
        else:
            objectives = Objective.query.filter_by(owner_id=current_user.id).all()

    objectives_data = [obj.to_dict() for obj in objectives]

    # 调用AI分析
    result = ai_service.analyze_progress(objectives_data)

    if result['success']:
        return jsonify({
            'objectives_count': len(objectives_data),
            'analysis': result['response']
        }), 200
    else:
        return jsonify({
            'error': 'Analysis failed',
            'details': result.get('error')
        }), 500

@bp.route('/team-summary', methods=['GET'])
@login_required
def team_summary():
    """团队状态总结（需要主管权限）"""
    if not current_user.is_manager():
        return jsonify({'error': 'Manager access required'}), 403

    # 获取团队状态
    team_members = current_user.get_team_members()
    team_member_ids = [member.id for member in team_members] + [current_user.id]

    team_status = []
    for user_id in team_member_ids:
        user = User.query.get(user_id)
        latest_status = StatusUpdate.query.filter_by(user_id=user_id)\
            .order_by(StatusUpdate.created_at.desc()).first()

        team_status.append({
            'user': user.to_dict(),
            'latest_status': latest_status.to_dict() if latest_status else None
        })

    # 调用AI总结
    result = ai_service.summarize_team_status(team_status)

    if result['success']:
        return jsonify({
            'team_size': len(team_status),
            'summary': result['response'],
            'raw_data': team_status
        }), 200
    else:
        return jsonify({
            'error': 'Summary failed',
            'details': result.get('error')
        }), 500

def _gather_context():
    """收集上下文数据"""
    context = {}

    # 获取用户相关的目标
    if current_user.is_manager():
        team_member_ids = [member.id for member in current_user.get_team_members()]
        team_member_ids.append(current_user.id)
        objectives = Objective.query.filter(Objective.owner_id.in_(team_member_ids))\
            .limit(20).all()
    else:
        objectives = Objective.query.filter_by(owner_id=current_user.id).all()

    context['objectives'] = [obj.to_dict() for obj in objectives]

    # 获取用户相关的项目
    if current_user.is_manager():
        projects = Project.query.filter(Project.owner_id.in_(team_member_ids))\
            .limit(20).all()
    else:
        projects = Project.query.filter_by(owner_id=current_user.id).all()

    context['projects'] = [proj.to_dict() for proj in projects]

    # 如果是主管，获取团队状态
    if current_user.is_manager():
        team_status = []
        for user_id in team_member_ids:
            user = User.query.get(user_id)
            latest_status = StatusUpdate.query.filter_by(user_id=user_id)\
                .order_by(StatusUpdate.created_at.desc()).first()

            if latest_status:
                team_status.append({
                    'user': user.full_name,
                    'status': latest_status.to_dict()
                })

        context['team_status'] = team_status

    return context